package com.example.airole.business.service.impl;

import com.example.airole.business.entity.Conversation;
import com.example.airole.business.service.ConversationService;
import com.example.airole.common.entity.ConversationMessage;
import com.example.airole.llm.entity.ChatMessage;
import com.example.airole.llm.entity.ChatRequest;
import com.example.airole.llm.entity.ChatResponse;
import com.example.airole.common.entity.Role;
import com.example.airole.llm.service.LLMService;
import com.example.airole.speech.entity.SpeechRecognitionRequest;
import com.example.airole.speech.entity.SpeechRecognitionResponse;
import com.example.airole.speech.service.SpeechRecognitionService;
import com.example.airole.tts.entity.TTSRequest;
import com.example.airole.tts.entity.TTSResponse;
import com.example.airole.tts.service.TTSService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 对话服务实现（不需要用户登录）
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class ConversationServiceImpl implements ConversationService {
    
    private final LLMService llmService;
    private final SpeechRecognitionService speechRecognitionService;
    private final TTSService ttsService;
    
    // 内存存储（实际项目中应使用数据库）
    private final ConcurrentHashMap<String, Conversation> conversations = new ConcurrentHashMap<>();
    private final ConcurrentHashMap<String, List<ConversationMessage>> conversationMessages = new ConcurrentHashMap<>();
    
    @Override
    public Conversation createConversation(String sessionId, String roleId, String title) {
        String conversationId = UUID.randomUUID().toString();
        
        Conversation conversation = Conversation.builder()
                .conversationId(conversationId)
                .sessionId(sessionId)
                .roleId(roleId)
                .title(title != null ? title : "新对话")
                .status(Conversation.ConversationStatus.ACTIVE)
                .messageCount(0)
                .createTime(LocalDateTime.now())
                .updateTime(LocalDateTime.now())
                .build();
        
        conversations.put(conversationId, conversation);
        conversationMessages.put(conversationId, new ArrayList<>());
        
        return conversation;
    }
    
    @Override
    public List<Conversation> getSessionConversations(String sessionId) {
        return conversations.values().stream()
                .filter(conv -> sessionId.equals(conv.getSessionId()))
                .filter(conv -> conv.getStatus() == Conversation.ConversationStatus.ACTIVE)
                .sorted((a, b) -> b.getCreateTime().compareTo(a.getCreateTime()))
                .toList();
    }
    
    @Override
    public Conversation getConversation(String conversationId, String sessionId) {
        Conversation conversation = conversations.get(conversationId);
        if (conversation != null && sessionId.equals(conversation.getSessionId())) {
            return conversation;
        }
        return null;
    }
    
    @Override
    public boolean updateConversationTitle(String conversationId, String title, String sessionId) {
        Conversation conversation = conversations.get(conversationId);
        if (conversation != null && sessionId.equals(conversation.getSessionId())) {
            conversation.setTitle(title);
            conversation.setUpdateTime(LocalDateTime.now());
            return true;
        }
        return false;
    }
    
    @Override
    public boolean deleteConversation(String conversationId, String sessionId) {
        Conversation conversation = conversations.get(conversationId);
        if (conversation != null && sessionId.equals(conversation.getSessionId())) {
            conversation.setStatus(Conversation.ConversationStatus.DELETED);
            conversation.setUpdateTime(LocalDateTime.now());
            return true;
        }
        return false;
    }
    
    @Override
    public boolean archiveConversation(String conversationId, String sessionId) {
        Conversation conversation = conversations.get(conversationId);
        if (conversation != null && sessionId.equals(conversation.getSessionId())) {
            conversation.setStatus(Conversation.ConversationStatus.ARCHIVED);
            conversation.setUpdateTime(LocalDateTime.now());
            return true;
        }
        return false;
    }
    
    @Override
    public ChatResponse sendTextMessage(String conversationId, String content, String sessionId, String roleId) {
        try {
            Conversation conversation = getConversation(conversationId, sessionId);
            if (conversation == null) {
                return ChatResponse.builder()
                        .success(false)
                        .errorMessage("对话不存在")
                        .build();
            }
            
            // 构建聊天请求
            ChatMessage userMessage = ChatMessage.builder()
                    .role("user")
                    .content(content)
                    .messageType("text")
                    .build();
            
            ChatRequest chatRequest = ChatRequest.builder()
                    .messages(List.of(userMessage))
                    .roleId(roleId)
                    .build();
            
            // 调用LLM服务
            ChatResponse response = llmService.chat(chatRequest);
            
            if (response.isSuccess()) {
                // 保存消息
                saveMessage(conversationId, content, null, ConversationMessage.MessageSender.USER, ConversationMessage.MessageType.TEXT);
                saveMessage(conversationId, response.getContent(), null, ConversationMessage.MessageSender.AI, ConversationMessage.MessageType.TEXT);
                
                // 更新对话
                updateConversationAfterMessage(conversationId);
            }
            
            return response;
            
        } catch (Exception e) {
            log.error("发送文本消息异常", e);
            return ChatResponse.builder()
                    .success(false)
                    .errorMessage("发送消息失败: " + e.getMessage())
                    .build();
        }
    }
    
    @Override
    public ChatResponse sendAudioMessage(String conversationId, MultipartFile audioFile, String sessionId, String roleId) {
        try {
            Conversation conversation = getConversation(conversationId, sessionId);
            if (conversation == null) {
                return ChatResponse.builder()
                        .success(false)
                        .errorMessage("对话不存在")
                        .build();
            }
            
            // 语音识别
            SpeechRecognitionResponse recognitionResponse = speechToText(audioFile);
            if (!recognitionResponse.isSuccess()) {
                return ChatResponse.builder()
                        .success(false)
                        .errorMessage("语音识别失败: " + recognitionResponse.getErrorMessage())
                        .build();
            }
            
            String recognizedText = recognitionResponse.getText();
            
            // 发送文本消息
            ChatResponse response = sendTextMessage(conversationId, recognizedText, sessionId, roleId);
            
            if (response.isSuccess()) {
                // 保存音频消息
                saveMessage(conversationId, recognizedText, null, ConversationMessage.MessageSender.USER, ConversationMessage.MessageType.AUDIO);
            }
            
            return response;
            
        } catch (Exception e) {
            log.error("发送语音消息异常", e);
            return ChatResponse.builder()
                    .success(false)
                    .errorMessage("发送语音消息失败: " + e.getMessage())
                    .build();
        }
    }
    
    @Override
    public List<ConversationMessage> getConversationMessages(String conversationId, String sessionId, int page, int size) {
        Conversation conversation = getConversation(conversationId, sessionId);
        if (conversation == null) {
            return new ArrayList<>();
        }
        
        List<ConversationMessage> messages = conversationMessages.get(conversationId);
        if (messages == null) {
            return new ArrayList<>();
        }
        
        // 简单的分页实现
        int start = page * size;
        int end = Math.min(start + size, messages.size());
        
        if (start >= messages.size()) {
            return new ArrayList<>();
        }
        
        return messages.subList(start, end);
    }
    
    @Override
    public SpeechRecognitionResponse speechToText(MultipartFile audioFile) {
        try {
            SpeechRecognitionRequest request = SpeechRecognitionRequest.builder()
                    .audioFile(audioFile)
                    .language("zh-CN")
                    .build();
            
            return speechRecognitionService.recognize(request);
            
        } catch (Exception e) {
            log.error("语音转文字异常", e);
            return SpeechRecognitionResponse.builder()
                    .success(false)
                    .errorMessage("语音转文字失败: " + e.getMessage())
                    .build();
        }
    }
    
    @Override
    public TTSResponse textToSpeech(String text) {
        try {
            TTSRequest request = TTSRequest.builder()
                    .text(text)
                    .language("zh")
                    .voice("0")
                    .speed(5.0)
                    .outputFormat("mp3")
                    .build();
            
            return ttsService.synthesize(request);
            
        } catch (Exception e) {
            log.error("文字转语音异常", e);
            return TTSResponse.builder()
                    .success(false)
                    .errorMessage("文字转语音失败: " + e.getMessage())
                    .build();
        }
    }
    
    /**
     * 保存消息
     */
    private void saveMessage(String conversationId, String content, String audioPath, 
                           ConversationMessage.MessageSender sender, ConversationMessage.MessageType messageType) {
        ConversationMessage message = ConversationMessage.builder()
                .messageId(UUID.randomUUID().toString())
                .conversationId(conversationId)
                .content(content)
                .audioPath(audioPath)
                .sender(sender)
                .messageType(messageType)
                .status(ConversationMessage.MessageStatus.SENT)
                .createTime(LocalDateTime.now())
                .updateTime(LocalDateTime.now())
                .build();
        
        List<ConversationMessage> messages = conversationMessages.get(conversationId);
        if (messages != null) {
            messages.add(message);
            
            // 保持最多10条消息
            if (messages.size() > 10) {
                messages.remove(0);
            }
        }
    }
    
    /**
     * 发送消息后更新对话
     */
    private void updateConversationAfterMessage(String conversationId) {
        Conversation conversation = conversations.get(conversationId);
        if (conversation != null) {
            List<ConversationMessage> messages = conversationMessages.get(conversationId);
            if (messages != null) {
                conversation.setMessageCount(messages.size());
            }
            conversation.setLastMessageTime(LocalDateTime.now());
            conversation.setUpdateTime(LocalDateTime.now());
        }
    }
}
